<?php
declare (strict_types=1);

namespace app\common\command;

use app\admin\model\MallCollage;
use app\admin\model\MallOrder;
use app\admin\model\SystemConfig;
use app\api\help\SendMsg;
use app\api\model\AllInPay;
use app\api\model\MallGoods;
use app\api\model\MallTradeRecordLog;
use app\api\model\MallUser;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Exception;
use think\facade\Config;
use think\facade\Db;
use think\facade\Log;
use Yansongda\Pay\Pay;

class Collage extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('Collage')
            ->setDescription('the Collage command');
    }
    
    protected function execute(Input $input, Output $output)
    {
        // 查询所有过期的拼团
        $time    = time();
        $collage = MallCollage::where([['end_time', '<', $time], ['fail_time', '=', 0], ['finish_time', '=', null]])->select()->toArray();
        if ( !empty($collage)) {
            $audit = SystemConfig::where('name', 'audit_return')->value('value');
            foreach ($collage as $key => $value) {
                $collageId = $value[ 'collage_id' ];
                try {
                    //开启事务
                    Db::startTrans();
                    if (false === MallCollage::where('collage_id', $collageId)->update(['fail_time' => time(), 'status' => 0])) {
                        _throwNewException('处理拼团失败');;
                    }
                    if (false === MallOrder::where([['collage_id', '=', $collageId], ['order_status', '=', 10]])->update(['order_status' => 40, 'collage_status' => 3, 'refund_status' => 10])) {
                        _throwNewException('处理订单失败');;
                    }
                    
                    //如果是自动审核
                    
                    
                    $orders = MallOrder::where([['collage_id', '=', $collageId], ['order_status', '=', 40]])->select()->toArray();
                    foreach ($orders as $k => $v) {
                        $balance        = MallUser::where('id', $v[ 'user_id' ])->value('balance');
                        $failure_reward = MallCollage::where('collage_id', $v[ 'collage_id' ])->value('failure_reward');
                        if ($audit == 0) {
                            //添加失败奖励
                            MallOrder::resolveFailureReward($failure_reward, $v[ 'user_id' ], $v[ 'id' ], $v[ 'collage_id' ]);
                            $modOrder = ['refund_status' => 40, 'collage_status' => 4, 'refund_time' => time()];
                            if ($v[ 'pay_price' ] > 0) {
                                $res = AllInPay::orderRefundInfo($v);
                                if ($res[ 'trxstatus' ] == '0000') {
                                    AllInPay::afterRefund($v);
                                } else {
                                    _throwNewException($res[ 'errmsg' ]);
                                }
                                
                            } else {
                                $surBalance                  = $balance + $v[ 'pay_balance' ];
                                //加上余额
                                if (false === MallUser::where([['id', '=', $v[ 'user_id' ]]])->update(['balance' => $surBalance])) {
                                    _throwNewException('订单退款失败');
                                }
                                //添加交易记录
                                MallTradeRecordLog::addRecord($v[ 'user_id' ], $v[ 'id' ], $v[ 'pay_balance' ], $surBalance, 11);
                               
                                
                            }
                            if (false === MallOrder::where('id', $v[ 'id' ])->update($modOrder)) {
                                _throwNewException('订单退款失败');
                            }
                        }
                    }
                    
                    
                    // 提交事务
                    Db::commit();
                } catch (Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    echo $e->getMessage();
                }
                
            }
            
        }
//        self::echo_curr_time('all done');
    }
    /**
     * 输出当前时间
     */
    public static function echo_curr_time($msg = '', $data = '')
    {
        echo date('Y-m-d H:i:s') . ' ' . $msg . ',' . json_encode($data), PHP_EOL;
    }
}
